'''
urlencode示例，百度搜索关键字，保存为：关键字.html到本地
'''
from urllib import request, parse
import requests

# 1、拼接url地址
word = input('请输入百度搜索的关键字：')
params = parse.urlencode({'wd': word})
url = 'http://www.baidu.com/s?{}'.format(params)
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52'}
# 2、发送请求获取响应内容
# req = request.Request(url=url, headers=headers)
# res = request.urlopen(req)
# html = res.read().decode()
res = requests.get(url=url, headers=headers)
html = res.text
# 3、保存到本地
filename = word + '.html'
with open(filename, 'w', encoding='utf-8') as f:
    f.write(html)
    print('保存成功！')
